﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebVideoServer
{
    public class DbConnectionProvider
    {
        protected ConnectionStringSettings m_CnnString = null;
        protected DbProviderFactory m_DbFactory = null;

        public virtual void LoadConfig(string cnnStrName)
        {
            m_DbFactory = null;
            m_CnnString = null;

            ConfigurationManager.RefreshSection("system.data");
            ConfigurationManager.RefreshSection("connectionStrings");

            m_CnnString = ConfigurationManager.ConnectionStrings[cnnStrName];

            try
            {
                m_DbFactory = DbProviderFactories.GetFactory(m_CnnString.ProviderName);
            }
            catch { }

            if (m_DbFactory == null)
            {
                DataSet section = ConfigurationManager.GetSection("system.data") as DataSet;
                if (section != null)
                {
                    DataTable table = section.Tables["DbProviderFactories"];
                    if (table != null)
                    {
                        foreach (DataRow row in table.Rows)
                        {
                            if (m_CnnString.ProviderName.Equals(row["Name"]))
                            {
                                m_DbFactory = DbProviderFactories.GetFactory(row);
                            }
                            if (m_DbFactory != null) break;
                        }
                    }
                }
            }
        }

        public virtual IDbConnection OpenDbConnection()
        {
            DbProviderFactory factory = m_DbFactory;
            ConnectionStringSettings setting = m_CnnString;

            IDbConnection conn = null;
            if (factory != null && setting != null)
            {
                conn = factory.CreateConnection();
                conn.ConnectionString = setting.ConnectionString;
                if (conn != null) conn.Open();
            }
            return conn;
        }
    }
}
